/**
 * 
 */
package com.zj.helloview.editor;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;

import com.zj.helloview.TableView;
import com.zj.helloview.View;
import com.zj.helloview.ViewPart1;
import com.zj.helloview.model.Category;

/**
 * @author Administrator
 * 
 */
public class CallEditor extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		System.out.println("called");
		// Get the view
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
		IWorkbenchPage page = window.getActivePage();
		TableView view = (TableView) page.findView(TableView.ID);
		// Get the selection
		ISelection selection = view.getSite().getSelectionProvider().getSelection();
		if (selection != null && selection instanceof IStructuredSelection) {
			Object obj = ((IStructuredSelection) selection).getFirstElement();
			// If we had a selection lets open the editor
			if (obj != null) {
				Category category = (Category) obj;
				CategoryEditorInput input = new CategoryEditorInput(category.getName());
				try {
					page.openEditor(input, CategoryEditor.ID);

				} catch (PartInitException e) {
					throw new RuntimeException(e);
				}
			}else {
				CategoryEditorInput input = new CategoryEditorInput("no selection");
				try {
					page.openEditor(input, CategoryEditor.ID);

				} catch (PartInitException e) {
					throw new RuntimeException(e);
				}
			}
		}
		return null;
	}

}
